﻿﻿using System;
using System.Linq;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.Display;
using ESRI.ArcGIS.DataSourcesFile;
using ESRI.ArcGIS.Geometry;
using System.Drawing;

namespace Arcgis
{
    public partial class SearchForm : Form
    {
        private IFeatureClass m_featureClass;
        private readonly Form1 m_mainForm;
        private IGraphicsContainer m_highlightGraphics;
        private ISimpleMarkerSymbol m_highlightSymbol;
        private IRgbColor m_outlineColor;

        public SearchForm(Form1 mainForm)
        {
            InitializeComponent();
            m_mainForm = mainForm;
            InitializeComponents();
            LoadFeatureClass();
            InitializeSymbols();
        }
        private void InitializeComponents()
        {
            this.Text = "景点查询";
            this.Size = new Size(400, 300);
            this.FormClosing += SearchForm_FormClosing;

            // 搜索框
            var txtSearch = new TextBox
            {
                Location = new System.Drawing.Point(20, 20),
                Size = new Size(200, 25),
                Text = "请输入景点名称(*/ω＼*)"
            };

            // 搜索按钮
            var btnSearch = new Button
            {
                Text = "搜索",
                Location = new System.Drawing.Point(230, 20),
                Size = new Size(80, 25)
            };
            btnSearch.Click += (s, e) => SearchFeatures(txtSearch.Text);

            // 结果列表
            var lstResults = new ListBox
            {
                Name = "lstResults",
                Location = new System.Drawing.Point(20, 60),
                Size = new Size(340, 180),
                Font = new Font("宋体", 10, FontStyle.Bold)
            };
            lstResults.DoubleClick += LstResults_DoubleClick;

            // 添加控件到窗体
            this.Controls.AddRange(new Control[] { txtSearch, btnSearch, lstResults });
        }
        private void InitializeSymbols()
        {
            // 初始化高亮符号
            m_highlightSymbol = new SimpleMarkerSymbolClass
            {
                Style = esriSimpleMarkerStyle.esriSMSCircle,
                Color = new RgbColorClass { Red = 255, Green = 0, Blue = 0, Transparency = 50 },
                Size = 12,
                Outline = true
            };

            // 初始化边框颜色
            m_outlineColor = new RgbColorClass { Red = 0, Green = 0, Blue = 0 };
            m_highlightSymbol.OutlineColor = m_outlineColor;
            m_highlightSymbol.OutlineSize = 2;
        }
        // 加载景点Shapefile
        private void LoadFeatureClass()
        {
            string shapefilePath = @"D:\MyGIS\sj\新建文件夹\长沙市景点数据.shp"; // 请确认实际路径

            try
            {
                if (!System.IO.File.Exists(shapefilePath))
                {
                    MessageBox.Show("景点数据文件不存在！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                IWorkspaceFactory workspaceFactory = new ShapefileWorkspaceFactoryClass();
                IFeatureWorkspace featureWorkspace = (IFeatureWorkspace)workspaceFactory.OpenFromFile(
                    System.IO.Path.GetDirectoryName(shapefilePath), 0);

                m_featureClass = featureWorkspace.OpenFeatureClass(
                    System.IO.Path.GetFileNameWithoutExtension(shapefilePath));
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载景点数据失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        // 执行搜索
        private void SearchFeatures(string keyword)
        {
            if (m_featureClass == null)
            {
                MessageBox.Show("窝们这里没有这个景点！(┬┬﹏┬┬)", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            ListBox lstResults = (ListBox)this.Controls[2];
            lstResults.Items.Clear();

            try
            {
                // 构建查询条件
                IQueryFilter queryFilter = new QueryFilterClass();
                queryFilter.WhereClause = $"NAME LIKE '%{keyword}%'"; // 假设字段名为NAME

                // 执行查询
                IFeatureCursor featureCursor = m_featureClass.Search(queryFilter, false);
                IFeature feature = featureCursor.NextFeature();

                // 遍历结果
                while (feature != null)
                {
                    string name = feature.get_Value(feature.Fields.FindField("NAME")).ToString();
                    lstResults.Items.Add(name); // 仅添加景点名称
                    feature = featureCursor.NextFeature();
                }

                // 释放资源
                Marshal.ReleaseComObject(featureCursor);

                if (lstResults.Items.Count == 0)
                {
                    MessageBox.Show("窝们这里没有这个景点！(┬┬﹏┬┬)", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            catch (COMException ex)
            {
                MessageBox.Show($"查询失败(0x{ex.ErrorCode:X8}): {ex.Message}",
                    "ArcGIS错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"查询失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        // 双击事件处理
        private void LstResults_DoubleClick(object sender, EventArgs e)
        {
            var lstResults = this.Controls.Find("lstResults", true).FirstOrDefault() as ListBox;
            if (lstResults?.SelectedItem == null) return;

            try
            {
                string selectedText = lstResults.SelectedItem.ToString();
                string name = selectedText.Split('-')[0].Trim();
                var feature = FindFeatureByName(name);
                if (feature == null) return;

                ClearHighlight();
                AddHighlight(feature);
                ZoomToFeature(feature);
                RefreshMap();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"定位失败: {ex.Message}");
            }
        }
        // 查找要素方法
        private IFeature FindFeatureByName(string name)
        {
            var queryFilter = new QueryFilterClass
            {
                WhereClause = $"NAME = '{name.Replace("'", "''")}'"
            };

            var cursor = m_featureClass.Search(queryFilter, false);
            try
            {
                return cursor.NextFeature();
            }
            finally
            {
                Marshal.ReleaseComObject(cursor);
            }
        }

        // 添加高亮图形
        private void AddHighlight(IFeature feature)
        {
            m_mainForm.SafeMapAction(mapControl =>
            {
                // 获取图形容器
                var graphicsContainer = mapControl.Map as IGraphicsContainer;
                graphicsContainer.DeleteAllElements();

                // 创建高亮符号（使用预定义的m_highlightSymbol）
                var markerElement = new MarkerElementClass
                {
                    Symbol = m_highlightSymbol
                };
                ((IElement)markerElement).Geometry = feature.ShapeCopy;

                // 添加图形
                graphicsContainer.AddElement((IElement)markerElement, 0);
                mapControl.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGraphics, null, null);
            });
        }

        // 清除高亮
        private void ClearHighlight()
        {
            if (m_highlightGraphics == null) return;
            m_highlightGraphics.DeleteAllElements();
            Marshal.ReleaseComObject(m_highlightGraphics);
            m_highlightGraphics = null;
        }

        // 定位到要素
        private void ZoomToFeature(IFeature feature)
        {
            m_mainForm.SafeMapAction(mapControl =>
            {
                IEnvelope env = feature.Shape.Envelope;
                env.Expand(1.5, 1.5, true);
                mapControl.Extent = env;
            });
        }
    
        private void RefreshMap()
        {
            m_mainForm.SafeMapAction(mapControl =>
            {
                mapControl.ActiveView.PartialRefresh(
                    esriViewDrawPhase.esriViewGeography | esriViewDrawPhase.esriViewGraphics,
                    null, null);
            });
        }

        private void SearchForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            // 释放COM对象
            if (m_featureClass != null)
            {
                Marshal.ReleaseComObject(m_featureClass);
                m_featureClass = null;
            }

            if (m_highlightSymbol != null)
            {
                Marshal.ReleaseComObject(m_highlightSymbol);
                m_highlightSymbol = null;
            }

            if (m_outlineColor != null)
            {
                Marshal.ReleaseComObject(m_outlineColor);
                m_outlineColor = null;
            }

            ClearHighlight();
        }

        private void SearchForm_Load(object sender, EventArgs e)
        {

        }
    }
}